﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Pavilion
{
    internal class PolygonAndPolygonIntersection
    {
        private PolygonCollisionData aCollisionData;
        private PolygonCollisionData bCollsionData;
        private PolygonPhysicalData APolygonData { get { return aCollisionData.PhysicalData as PolygonPhysicalData; } }
        private PolygonPhysicalData BPolygonData { get { return bCollsionData.PhysicalData as PolygonPhysicalData; } }
        private bool checkIntersection;

        public PolygonAndPolygonIntersection(PolygonCollisionData aCollisionData, PolygonCollisionData bCollsionData)
        {
            this.checkIntersection = true;
            this.aCollisionData = aCollisionData;
            this.bCollsionData = bCollsionData;

            APolygonData.PhysicalFormChanged += new Action<PhysicalData>(PhysicalData_PhysicalFormChanged);
            BPolygonData.PhysicalFormChanged += new Action<PhysicalData>(PhysicalData_PhysicalFormChanged);
        }

        internal void UpdateIntersection()
        {
            if (!checkIntersection)
                return;

            checkIntersection = false;

            if (APolygonData.PhysicalBounds.Intersects(BPolygonData.PhysicalBounds))
            {
                aCollisionData.AddPolygon(BPolygonData);
                bCollsionData.AddPolygon(APolygonData);
            }
            else
            {
                aCollisionData.RemovePolygon(BPolygonData);
                bCollsionData.RemovePolygon(APolygonData);
            }
        }

        private void PhysicalData_PhysicalFormChanged(PhysicalData physicalData) { checkIntersection = true; }
    }
}
